package com.jk.common.utils;

import com.jk.common.exception.ServiceException;
import java.lang.management.ManagementFactory;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.Calendar;
import java.util.Date;
import java.util.Objects;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.util.Assert;

/**
 * 时间工具类
 *
 * @author happy
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    public static Calendar instance = Calendar.getInstance();

    public static final String ZERO = "0";
    public static final int NUM_TEN = 10;
    public static final int NUM_ONE = 1;

    public static Date addDays(Date date, int days) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, days);
        return cal.getTime();
    }

    public static Date subDays(Date date, int days) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, days * -1);
        return cal.getTime();
    }

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate() {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate() {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime() {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow() {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format) {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date) {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date) {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts) {
        try {
            return new SimpleDateFormat(format).parse(ts);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str) {
        if (str == null) {
            return null;
        }
        try {
            return parseDate(str.toString(), parsePatterns);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate() {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算相差天数
     */
    public static int differentDaysByMillisecond(Date date1, Date date2) {
        return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));
    }

    /**
     * 计算时间差
     *
     * @param endDate   最后时间
     * @param startTime 开始时间
     * @return 时间差（天/小时/分钟）
     */
    public static String timeDistance(Date endDate, Date startTime) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - startTime.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 增加 LocalDateTime ==> Date
     */
    public static Date toDate(LocalDateTime temporalAccessor) {
        ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 增加 LocalDate ==> Date
     */
    public static Date toDate(LocalDate temporalAccessor) {
        LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
        ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 获取当前年
     */
    public static Integer getYear() {
        int year = instance.get(Calendar.YEAR);
        return year;
    }

    /**
     * 获取当前周
     */
    public static Integer getWeek() {
        int week = instance.get(Calendar.WEEK_OF_YEAR);
        return week;
    }

    /**
     * 获取当前年月周：20240112
     */
    public static String getWeekOfYear() {
        //当前周数
        int week = instance.get(Calendar.WEEK_OF_YEAR);
        //当前年数
        int year = instance.get(Calendar.YEAR);
        return String.format("%04d%02d", year, week);
    }

    /**
     * 获取上周 年月周：20240111
     */
    public static String getLastWeekOfYear() {
        //当前周数
        int week = instance.get(Calendar.WEEK_OF_YEAR);
        //当前年数
        int year = instance.get(Calendar.YEAR);
        return String.format("%04d%02d", year, week - 1);
    }

    public static boolean isLegalDate(String date, int length, String format) {
        if (date == null || date.length() != length) {
            return false;
        }
        try {
            DateFormat formatter = new SimpleDateFormat(format);
            // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期，比如2018-02-29会被接受，并转换成2018-03-01
            //"2019022 "|"201902 2" 这两种也能被Date转化，所以最后需要用date.equals(formatter.format(date1));
            formatter.setLenient(false);
            Date date1 = formatter.parse(date);

            return date.equals(formatter.format(date1));
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean isLegalLocalDateTime(String date, String format) {
        if (date == null || date.isEmpty()) {
            return false;
        }
        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
            LocalDateTime dateTime = LocalDateTime.parse(date, formatter);
            // 验证解析后的日期时间格式化后是否与原字符串相同
            return date.equals(formatter.format(dateTime));
        } catch (DateTimeParseException e) {
            return false;
        }
    }

    /**
     * string->LocalDateTime
     *
     * @param recordTime
     * @return
     */

    public static LocalDateTime toLocalDateTime(String recordTime,DateTimeFormatter formatter) {

        if (Objects.isNull(recordTime)) {
            return null;
        }
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return LocalDateTime.parse(recordTime, formatter);

    }

    public static LocalDate toLocalDate(String recordTime) {

        if (Objects.isNull(recordTime)) {
            return null;
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        return LocalDate.parse(recordTime, formatter);

    }

    /**
     * 获取天数
     *
     * @param frequency 频次
     * @param unit      单位
     * @return
     */
    public static Integer getDay(Long frequency, String unit) {
        Assert.notNull(frequency, "frequency is not null");
        Assert.notNull(unit, "unit is not null");
        switch (unit) {
            case "day":
                return frequency.intValue();
            case "hour":
                return frequency.intValue() / 24;
            default:
                throw new ServiceException("getDay error frequency: " + frequency + "unit: " + unit);
//                return null;
        }
    }

    /**
     * 获取当前月份的第一天。
     *
     * @return 返回当前月份第一天的 LocalDate。
     */
    public static LocalDate findFirstDayOfCurrentMonth() {
        // 获取当前日期
        LocalDate today = LocalDate.now();

        // 调整到当前月份的第一天
        return today.withDayOfMonth(1);
    }

    /**
     * 获取当前月份的最后一天。
     *
     * @return 返回当前月份第一天的 LocalDate。
     */
    public static LocalDate findLastDayOfCurrentMonth() {
        // 获取当前日期
        LocalDate today = LocalDate.now();

        // 调整到当前月份的最后一天
        return today.with(TemporalAdjusters.lastDayOfMonth());
    }

    /**
     * 根据当前日期找到本周周一的日期。
     *
     * @return 返回本周周一的 LocalDate。
     */
    public static LocalDate findThisWeekMonday() {
        // 获取当前日期
        LocalDate today = LocalDate.now();

        // 调整到本周的周一，如果今天是周一，则保持不变
        return today.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
    }

    public static LocalDate findThisWeekSunday() {
        LocalDate today = LocalDate.now();
        return today.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
    }

    /**
     * 将任意对象转换为 LocalDate，支持 String 和 LocalDate 两种类型
     */
    public static LocalDate parseToLocalDate(Object dateObj) {
        if (dateObj == null) {
            return null;
        }

        if (dateObj instanceof LocalDate) {
            return (LocalDate) dateObj;
        } else if (dateObj instanceof String) {
            String dateStr = (String) dateObj;
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            try {
                return LocalDate.parse(dateStr, formatter);
            } catch (Exception e) {
                throw new IllegalArgumentException("日期格式错误，请使用 yyyy-MM-dd 格式: " + dateStr, e);
            }
        } else {
            throw new IllegalArgumentException("不支持的日期类型: " + dateObj.getClass());
        }
    }


    public static String timeSubtraction (String startTime,LocalDateTime now) {
        // 1. 解析 startTime 为 LocalTime
        LocalTime start = LocalTime.parse(startTime, DateTimeFormatter.ofPattern("HH:mm:ss"));

        // 2. 将当前时间 now 拆解为 LocalDate 和 LocalTime
        LocalDate currentDate = now.toLocalDate();
        LocalTime currentTime = now.toLocalTime();

        // 3. 计算时间差（当前时间是否小于 startTime）
        if (currentTime.isBefore(start)) {
            // 如果当前时间小于 startTime，则需要向前借一天（减去1天）
            currentDate = currentDate.minusDays(1);
            // 计算跨天的时间差：24小时 - (startTime - currentTime)
            long diffHours = 24 - ChronoUnit.HOURS.between(currentTime, start);
            long diffMinutes = 60 - ChronoUnit.MINUTES.between(currentTime, start) % 60;
            long diffSeconds = 60 - ChronoUnit.SECONDS.between(currentTime, start) % 60;

            // 调整计算精度（避免负值）
            LocalDateTime adjustedDateTime = now.minusDays(1)
                    .minusHours(diffHours)
                    .minusMinutes(diffMinutes)
                    .minusSeconds(diffSeconds);
            currentDate = adjustedDateTime.toLocalDate();
        } else {
            // 直接减去时间差（无需跨天）
            LocalDateTime resultDateTime = now.minusHours(start.getHour())
                    .minusMinutes(start.getMinute())
                    .minusSeconds(start.getSecond());
            currentDate = resultDateTime.toLocalDate();
        }

        // 4. 将结果转换为字符串（ISO 格式 yyyy-MM-dd）
//        log.info("Result Date: " + currentDate.toString());
        return currentDate.toString();
    }
}
